# -*- coding: utf-8 -*-
import base64
import hashlib
import hmac
import json
import random
import time
from collections import OrderedDict

import requests
from django.conf import settings
from django.template import Context
from django.template.loader import get_template

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '866': {
        # 风云宝到卡 alipay 0.75% 100-3000 witch
        'API_KEY': 'fYiWYjlfw9A3sDpQ98au1hSLnoAYuci1tpNjlMsZMpPnp60AACl1l9s5c7CioFNS',
        'gateway': 'https://www.dsdfpay.com/dsdf/api/place_order',
        'query_gateway': 'https://www.dsdfpay.com/dsdf/api/query_order',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s, key):
    dig = hmac.new(key, msg=s, digestmod=hashlib.sha1).digest()
    dig64 = base64.b64encode(dig).decode()
    return dig64


def generate_sign(d, key):
    s = 'cid={}&uid={}&time={}&amount={}&order_id={}'.format(
        d['cid'], d['uid'], d['time'], d['amount'], d['order_id']
    )
    return _gen_sign(s, key)


def generate_notify_sign(d, key):
    s = 'order_id={}&amount={}&verified_time={}'.format(
        d['order_id'], d['amount'], d['verified_time']
    )
    return _gen_sign(s, key)


def generate_query_sign(d, key):
    s = json.dumps(d)
    return _gen_sign(s, key)


def verify_notify_sign(params, key):
    sign = params['qsign']
    params.pop('qsign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("fengyunpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay_to_bank':
        return 'remit'
    elif service == 'qrcode':
        return 'qrcode'
    return 'remit'


def _get_meta_data(service):
    if service == 'alipay_to_bank':
        return {
            "QuickOrder": "Alipay2Bank"
        }
    elif service == 'qrcode':
        return {
            "QuickOrder": "WX2Bank"
        }
    return {
        "QuickOrder": "Alipay2Bank"
    }


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _fix_pay_amount(pay, pay_amount):
    extend = json.loads(pay.extend or '{}')
    if 10 <= pay_amount == int(pay_amount):
        discount = random.randint(1, 10)
        pay_amount = pay_amount - float(discount) / 100
        extend.update({'discount': str(float(discount) / 100)})
        order_db.fill_extend(pay.id, extend)
    return pay_amount


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('cid', app_id),
        ('uid', pay.user_id),
        ('time', int(time.time())),
        ('amount', '%.2f' % pay_amount),
        ('order_id', str(pay.id)),
        ('category', _get_pay_type(service)),
        ('ip', _get_device_ip(info)),
        ('from_bank_flag', 'ALIPAY'),
        ('comment', 'FengYun_Charge'),
        ('meta_data', _get_meta_data(service)),
    ))
    parameter_dict['qsign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("fengyunpay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['order_id'])
    headers = {'Content-Type': 'application/json'}
    response = requests.post(_get_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=3)
    _LOGGER.info('fengyunpay create rsp, %s, pay.id: %s', response.text, pay.id)

    data = {}
    data['title'] = u'风云支付'
    data['qrurl'] = json.loads(response.text)['data']['qrurl']
    data['amount'] = json.loads(response.text)['data']['amount']
    t = get_template('qr_alipay.html')
    html = t.render(Context(data))
    cache_id = redis_cache.save_html(pay.id, html)
    _LOGGER.info("fengyunpay create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = json.loads(request.body)
    _LOGGER.info("fengyunpay notify data: %s, order_id is: %s", data, data['order_id'])
    verify_notify_sign(data, api_key)
    pay_id = data['order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('fengyunpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['cmd'])
    trade_no = str(data['mer_order_id'])
    total_fee = float(data['amount']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 0 未处理 1 交易成功 2 支付失败 3 关闭交易 4 支付超时
    if trade_status == 'order_success' and total_fee > 0.0:
        _LOGGER.info('fengyunpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('cid', app_id),
        ('order_id', str(pay_order.id)),
        ('time', int(time.time())),
    ))
    _LOGGER.info('fengyunpay query data is: %s, order_id is: %s', json.dumps(parameter_dict),
                 parameter_dict['order_id'])
    sign_string = generate_query_sign(parameter_dict, api_key)
    headers = {'Content-Type': 'application/json', 'Content-Hmac': sign_string}
    response = requests.post(_get_query_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=3)
    _LOGGER.info('fengyunpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['order']['status'])
        total_fee = float(data['order']['amount'])
        trade_no = data['order']['mer_order_id']
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        if trade_status == 'verified':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('fengyunpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
